<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【JDK源码笔记】- CyclicBarrier 不就是比 CountDownLatch 多了个回环么？ | 程序员小航</title><meta name="keywords" content="源码笔记,JDK"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="看完 CountDownLatch 正准备表示一番，突然看到了一个 CyclicBarrier —— 回环屏障。沃特？回环还屏障？说比 CountDownLatch 要多一个回环，那咱可得瞧一瞧，看一看了！">
<meta property="og:type" content="article">
<meta property="og:title" content="【JDK源码笔记】- CyclicBarrier 不就是比 CountDownLatch 多了个回环么？">
<meta property="og:url" content="https://liuzhihang.com/2020/09/13/source-code-cyclicbarrier.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="看完 CountDownLatch 正准备表示一番，突然看到了一个 CyclicBarrier —— 回环屏障。沃特？回环还屏障？说比 CountDownLatch 要多一个回环，那咱可得瞧一瞧，看一看了！">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/CyclicBarrier-cover-HDbgaV.jpeg">
<meta property="article:published_time" content="2020-09-12T17:30:00.000Z">
<meta property="article:modified_time" content="2020-12-27T09:23:14.595Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="源码笔记">
<meta property="article:tag" content="JDK">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/CyclicBarrier-cover-HDbgaV.jpeg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2020/09/13/source-code-cyclicbarrier"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【JDK源码笔记】- CyclicBarrier 不就是比 CountDownLatch 多了个回环么？',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-27 17:23:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/CyclicBarrier-cover-HDbgaV.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【JDK源码笔记】- CyclicBarrier 不就是比 CountDownLatch 多了个回环么？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-09-12T17:30:00.000Z" title="发表于 2020-09-13 01:30:00">2020-09-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-27T09:23:14.595Z" title="更新于 2020-12-27 17:23:14">2020-12-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/JDK/">JDK</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【JDK源码笔记】- CyclicBarrier 不就是比 CountDownLatch 多了个回环么？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/09/13/source-code-cyclicbarrier.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p><strong>前言</strong></p>
<br>

<p>看完 CountDownLatch 正准备表示一番，突然看到了一个 CyclicBarrier —— 回环屏障。沃特？回环还屏障？说比 CountDownLatch 要多一个回环，那咱可得瞧一瞧，看一看了！</p>
</blockquote>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>一个同步辅助，它允许一组线程的所有等待彼此达成共同屏障点。 </p>
<p>CyclicBarrier 在涉及固定线程数且必须等待彼此的程序非常有用。 </p>
<p>该屏障被称为回环屏障 ，因为它在等待的线程被释放后可以被重新利用。</p>
<p>CyclicBarrier 支持一个可选的 Runnable 命令，该命令在障碍中的最后一个线程到达之后，但在释放任何线程之前，每个屏障点运行一次。</p>
<p>此屏障操作对于在任何一方继续之前更新共享状态很有用。</p>
<p>通过上面的源码注释基本可以得出以下结论：</p>
<ol>
<li>CyclicBarrier 和 CountDownLatch 类似，但它是一组线程等待，直到在其他线程中执行的一组操作完成为止。</li>
<li>CountDownLatch 是计数递减，结束后再调用 await 或者 countdown 都会立即返回，但是 CyclicBarrier 可以重置屏障。</li>
<li>CyclicBarrier 还可以传入参数 Runnable ，Runnable 会在释放线程之前执行。</li>
</ol>
<h4 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h4><p>既然上面总结了三个结论，下面当然从三个方面演示如何使用的：</p>
<p><strong>- 屏障功能</strong> </p>
<pre><code class="java">public class CyclicBarrierTest &#123;

    private static final CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(11);

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException &#123;

        ExecutorService pool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue&lt;&gt;(1024),
                new ThreadFactoryBuilder().setNameFormat(&quot;Thread-pool-%d&quot;).build(),
                new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i &lt; 10; i++) &#123;

            pool.submit(() -&gt; &#123;

                try &#123;
                    System.out.println(Thread.currentThread().getName() + &quot; 开始执行&quot;);
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getName() + &quot; 执行结束，准备调用 await&quot;);
                    CYCLIC_BARRIER.await();
                &#125; catch (InterruptedException | BrokenBarrierException e) &#123;
                    e.printStackTrace();
                &#125;

            &#125;);

        &#125;

        System.out.println(&quot;主线程执行 —————————————— &gt;&gt;&gt;&quot;);

        CYCLIC_BARRIER.await();

        System.out.println(&quot;主线程继续执行 —————————————— &gt;&gt;&gt;&quot;);

        pool.shutdown();

    &#125;
&#125;</code></pre>
<p>通过上面代码其实模拟了个类似 CountDownLatch 的功能，让所有线程等待，直到都调用 await 之后，各个线程继续执行，同时主线程也继续往下执行。</p>
<p>不过相对 CountDownLatch 的指定一个线程或多个等待，直到其他线程执行结束，等待的线程才继续执行来说，CyclicBarrier 相对来说还是逊色。</p>
<p>差别总结如下：</p>
<ol>
<li>CountDownLatch 是指定等待的线程，其他线程进行 countDown，等计数为 0 时，等待的线程继续执行。</li>
<li>CyclicBarrier 是一组线程调用 await 进行等待，当所有的都进入等待的时候，这一组就会一起冲破屏障继续执行。</li>
</ol>
<p><strong>- 回环功能</strong></p>
<pre><code class="java">public class CyclicBarrierTest2 &#123;

    private static final CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(5);

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException &#123;

        ExecutorService pool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue&lt;&gt;(1024),
                new ThreadFactoryBuilder().setNameFormat(&quot;Thread-pool-%d&quot;).build(),
                new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i &lt; 5; i++) &#123;

            pool.submit(() -&gt; &#123;

                try &#123;
                    System.out.println(Thread.currentThread().getName() + &quot; 开始执行&quot;);
                    CYCLIC_BARRIER.await();

                    System.out.println(Thread.currentThread().getName() + &quot; 冲破屏障 &gt;&gt;&gt; 1&quot;);
                    CYCLIC_BARRIER.await();

                    System.out.println(Thread.currentThread().getName() + &quot; 冲破屏障 &gt;&gt;&gt;&gt;&gt; 2&quot;);
                    CYCLIC_BARRIER.await();
                &#125; catch (InterruptedException | BrokenBarrierException e) &#123;
                    e.printStackTrace();
                &#125;

            &#125;);

        &#125;

        pool.shutdown();
    &#125;
&#125;</code></pre>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://liuzhihang.com/oss/pic/article/carbon-gzpBD4.png" alt="carbon-gzpBD4"></p>
<p>上面演示的回环的用法。</p>
<p><strong>- 回环 Runnable</strong></p>
<p>这块只需要在声明的 CyclicBarrier 修改为以下即可：</p>
<pre><code class="java">private static final CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(5, new Runnable() &#123;
    @Override
    public void run() &#123;
        System.out.println(&quot;执行一次 Runnable &quot;);
    &#125;
&#125;);</code></pre>
<p>打印结果如下：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://liuzhihang.com/oss/pic/article/carbon1-lHnKnA.png" alt="carbon1-lHnKnA"></p>
<p>可以看出只是在下一个计数开始之前，先执行 Runnable 。至于是不是在释放屏障之前，那很容易，直接 Debug 走一遭就知道了！专门录制了个视频：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://liuzhihang.com/oss/pic/article/cyclicBarrier-vl-5Bz3Xa.mov" alt="cyclicBarrier-vl-5Bz3Xa"></p>
<p>通过 debug 可以看出<strong>Runnable 会在释放线程之前执行</strong>。</p>
<h4 id="问题疑问？"><a href="#问题疑问？" class="headerlink" title="问题疑问？"></a>问题疑问？</h4><ol>
<li>CyclicBarrier 和 AQS 有什么关系？</li>
<li>CyclicBarrier 的实现原理是什么？</li>
<li>CyclicBarrier 是如何实现回环的？</li>
</ol>
<p>下面就带着疑问去源码阅读，一探究竟！</p>
<h3 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h3><h4 id="基本结构"><a href="#基本结构" class="headerlink" title="基本结构"></a>基本结构</h4><p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://liuzhihang.com/oss/pic/article/CleanShot-2020-09-12-KFzaCR0G@2x-seVhre.png" alt="CleanShot-2020-09-12-KFzaCR0G@2x-seVhre"></p>
<p>通过 UML 乍一看，CyclicBarrier 和 AQS 并无什么关系，那下面开始从<strong>参数</strong>、<strong>构造器</strong>、<strong>await()方法</strong>分别看源码。</p>
<h4 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h4><pre><code class="java">public class CyclicBarrier &#123;

    /**
     * 屏障的每次使用都表示为一个生成实例。
     * broken 表示屏障是否被打破。
     */
    private static class Generation &#123;
        boolean broken = false;
    &#125;

    /** 锁 */
    private final ReentrantLock lock = new ReentrantLock();
    /** 条件等待，直到屏障 */
    private final Condition trip = lock.newCondition();
    /** 等待计数 */
    private final int parties;
    /* The command to run when tripped */
    private final Runnable barrierCommand;
    /** 当前 generation 新创建的*/
    private Generation generation = new Generation();
    /** 仍在等待的 parties 数量，递减 为 0 会重置 */
    private int count; 
&#125;
</code></pre>
<p>通过上面可以看出：</p>
<p>内部使用了一个静态类 Generation ，它有什么功能呢？通过注释了解到，每次使用屏障的时候都会生成，具体有什么用，其实就是用来标示屏障是否被打破。</p>
<p>内部还有一个 parties 表示等待计数，count 表示仍在等待的计数。</p>
<p>那就继续往下看吧！</p>
<h4 id="构造器"><a href="#构造器" class="headerlink" title="构造器"></a>构造器</h4><pre><code class="java">public CyclicBarrier(int parties, Runnable barrierAction) &#123;
    if (parties &lt;= 0) throw new IllegalArgumentException();
    this.parties = parties;
    this.count = parties;
    this.barrierCommand = barrierAction;
&#125;</code></pre>
<p>这里的入参有两个：</p>
<ul>
<li>parties（等待计数）：记录多少个线程调用 await 之后，才会一起打破屏障。</li>
<li>barrierAction：冲破屏障前执行的行为。</li>
<li>但是会同时对 parties 和 count 赋值为传入的 parties。</li>
</ul>
<p>单参数构造，其实就是将 barrierAction 赋值为 null。</p>
<h4 id="await-方法"><a href="#await-方法" class="headerlink" title="await() 方法"></a>await() 方法</h4><p>在示例中用的 <strong>await()</strong> 方法， 那就从 <strong>await()</strong> 方法入手：</p>
<pre><code class="java">public int await() throws InterruptedException, BrokenBarrierException &#123;
    try &#123;
        return dowait(false, 0L);
    &#125; catch (TimeoutException toe) &#123;
        throw new Error(toe); // cannot happen
    &#125;
&#125;</code></pre>
<p>await() 才是重头戏， 先来根据源码注释，了解是干嘛的，看看作者怎么讲：</p>
<ol>
<li>等到所有各方都在此障碍上调用await。</li>
<li>如果当前线程不是最后到达的线程，则出于线程调度目的将其禁用，并使其处于休眠状态，直到发生以下情况之一：<ol>
<li>最后一个线程到达；</li>
<li>其他一些线程中断当前线程；</li>
<li>其他一些线程中断其他正在等待的线程之一；</li>
<li>等待屏障的时候其他线程超时；</li>
<li>其他一些线程在此屏障上调用 reset。</li>
</ol>
</li>
</ol>
<p>看到这些，咱们最想看的当然是 2.1 ，等待最后一个线程到达屏障，之后所有的线程一起继续执行。</p>
<pre><code class="java">
private int dowait(boolean timed, long nanos)
    throws InterruptedException, BrokenBarrierException,
            TimeoutException &#123;

    // 加锁
    final ReentrantLock lock = this.lock;
    lock.lock();
    try &#123;

        // 在这里用到了这个代
        final Generation g = generation;

        if (g.broken)
            throw new BrokenBarrierException();
        // 线程终中断标示
        if (Thread.interrupted()) &#123;
            breakBarrier();
            throw new InterruptedException();
        &#125;

        // 对计数进行递减
        int index = --count;
        // 如果是 0 则
        if (index == 0) &#123;  // tripped
            boolean ranAction = false;
            try &#123;
                final Runnable command = barrierCommand;
                // 不是 null 先执行行为
                if (command != null)
                    // 这里不是新开线程
                    command.run();
                ranAction = true;
                // 下一代
                nextGeneration();
                return 0;
            &#125; finally &#123;
                // 任务未成功时，即 ranAction 还是 false 打破屏障
                if (!ranAction)
                    breakBarrier();
            &#125;
        &#125;

        // loop until tripped, broken, interrupted, or timed out
        // 自旋
        for (;;) &#123;
            try &#123;
                // 没有设置超时时间
                if (!timed)
                // 进入等待
                    trip.await();
                else if (nanos &gt; 0L)
                    nanos = trip.awaitNanos(nanos);
            &#125; catch (InterruptedException ie) &#123;
                if (g == generation &amp;&amp; ! g.broken) &#123;
                    breakBarrier();
                    throw ie;
                &#125; else &#123;
                    Thread.currentThread().interrupt();
                &#125;
            &#125;

            if (g.broken)
                throw new BrokenBarrierException();
            // 已经下一代了
            if (g != generation)
                return index;

            if (timed &amp;&amp; nanos &lt;= 0L) &#123;
                breakBarrier();
                throw new TimeoutException();
            &#125;
        &#125;
    &#125; finally &#123;
        lock.unlock();
    &#125;
&#125;</code></pre>
<p>这一大坨代码，完全没有看的欲望，直接划过去吧！</p>
<p>所以…… 直接看到了这里吧。</p>
<p>代码还是要阅读的，分开来看（异常流程省略）：</p>
<ol>
<li>使用了 ReentrantLock 互斥锁，因此对 count、broken 的修改是原子性的。</li>
<li>对 count 进行 –count 操作，这样就理解为什么说 count 是仍在等待的计数，或者说还有多少才能到达屏障点。</li>
<li>当 count 为 0 ，表示到达屏障点了<ol>
<li><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://liuzhihang.com/oss/pic/article/cyclicbarrier-amQMu4.png" alt="cyclicbarrier-amQMu4"></li>
<li>command 不为 null，会先执行 **command.run()**， 值得注意的是这里并不是新开了个线程。</li>
<li>**nextGeneration()**开始新的下一代，即重置 count 为 parties。</li>
<li>在 finally 里面使用 <strong>breakBarrier()</strong> 打破屏障。</li>
</ol>
</li>
<li>当 count 不是 0<ol>
<li>自旋，直到是 0.</li>
</ol>
</li>
</ol>
<p>这后面还有两个方法不能少：</p>
<pre><code class="java">private void nextGeneration() &#123;
    // 唤醒线程
    trip.signalAll();
    // 更新 count 为 parties
    count = parties;
    // 更新 Generation
    generation = new Generation();
&#125;</code></pre>
<pre><code class="java">// 打破屏障，并唤醒全部
private void breakBarrier() &#123;
    generation.broken = true;
    count = parties;
    trip.signalAll();
&#125;</code></pre>
<h4 id="reset"><a href="#reset" class="headerlink" title="reset()"></a>reset()</h4><pre><code class="java">
public void reset() &#123;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try &#123;
        breakBarrier();   // break the current generation
        nextGeneration(); // start a new generation
    &#125; finally &#123;
        lock.unlock();
    &#125;
&#125;</code></pre>
<p>将屏障重置为其初始状态，reset() 方法其实还是调用的 breakBarrier() 和 nextGeneration()，前者时打破当前代，后者是开始新的一轮。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><strong>Q: CyclicBarrier 和 AQS 有什么关系？</strong><br><strong>A:</strong> 通过阅读源码，其实发现是使用了 ReentrantLock 互斥锁 以及 Condition 的等待唤醒功能。</p>
<p><strong>Q: CyclicBarrier 的实现原理是什么？</strong><br><strong>A:</strong> 内部含有两个计数，分别是 parties 和 count ，初始是二者相等，当有线程调用 await() 时，count 递减，只要 count 不为 0 ， 就会阻塞线程，直到 count 递减为 0 时，此时会所有线程一起释放，同时将 count 重置为 parties。</p>
<p><strong>Q: CyclicBarrier 是如何实现回环的？</strong><br><strong>A:</strong> 使用两个计数，count 递减，当 count 为 0 时，会重置为 parties，从而达到回环效果。</p>
<p><strong>Q: 为什么 count 的 –count 操作没有使用 CAS？</strong><br><strong>A:</strong> 因为已经 lock.lock() 了，使用了 ReentrantLock 锁能够保证 count 的原子性。</p>
<h4 id="CyclicBarrier-和-CountDownLatch-的区别"><a href="#CyclicBarrier-和-CountDownLatch-的区别" class="headerlink" title="CyclicBarrier 和 CountDownLatch 的区别"></a>CyclicBarrier 和 CountDownLatch 的区别</h4><ol>
<li>回环：CyclicBarrier 可以回环，重新计数。CountDownLatch 只能一轮。</li>
<li>计数器：CyclicBarrier 的计数器自己维护递减， CountDownLatch 的计数器维护则是交给使用者。</li>
<li>阻塞线程：CyclicBarrier 阻塞的是自身，当到达屏障后，所有被阻塞的线程一起释放。CountDownLatch 可以指定阻塞线程。</li>
</ol>
<h4 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a>结束语</h4><p>本文主要介绍了 CyclicBarrier 的常用方式，通过源码方式，分析如何达到屏障以及回环的效果。不对之处，请多指正。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2020/09/13/source-code-cyclicbarrier.html">https://liuzhihang.com/2020/09/13/source-code-cyclicbarrier.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><a class="post-meta__tags" href="/tags/JDK/">JDK</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/CyclicBarrier-cover-HDbgaV.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/09/19/work-trans-refund-table.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/LDZJYc-IFUqcP.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【工作笔记】- 你有没有想过为什么交易和退款要拆开不同的表？</div></div></a></div><div class="next-post pull-right"><a href="/2020/09/06/source-tool-drawio.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/drawio-bezZS1.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【工具册】- 给大家介绍下，这是我的流程图软件 —— draw.io</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/12/source-code-aqs.html" title="【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/aqs-uhgQnu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-12</div><div class="title">【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)</div></div></a></div><div><a href="/2020/09/27/source-code-arrayblockingqueue.html" title="【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ArrayBlockingQueue-cover-ESuNmo.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-27</div><div class="title">【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue</div></div></a></div><div><a href="/2020/06/12/source-code-cas.html" title="【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">基本使用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E7%96%91%E9%97%AE%EF%BC%9F"><span class="toc-text">问题疑问？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-text">源码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-text">基本结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%82%E6%95%B0"><span class="toc-text">参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9E%84%E9%80%A0%E5%99%A8"><span class="toc-text">构造器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#await-%E6%96%B9%E6%B3%95"><span class="toc-text">await() 方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#reset"><span class="toc-text">reset()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#CyclicBarrier-%E5%92%8C-CountDownLatch-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">CyclicBarrier 和 CountDownLatch 的区别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E6%9D%9F%E8%AF%AD"><span class="toc-text">结束语</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: 'c331f454e27ae6916e4ab522533ebf72',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>